const app = getApp();
import Poster from '../../../wxa-plugin-canvas/miniprogram_dist/poster/poster';

function promisify(fn) {
  return function(obj = {}) {
    return new Promise((resolve, reject) => {
      obj.success = function(res) {
        resolve(res)
      }

      obj.fail = function(res) {
        reject(res)
      }
      fn(obj)
    })
  }
}
Page({
  /**
   * 异步生成海报
   */
  onCreatePoster() {
    // setData配置数据
    this.setData({posterConfig: this.data.posterConfig}, () => {
      Poster.create(true, this);
    });
  },

  onPosterSuccess(e) {
    const { detail } = e;
    console.log(detail);
    this.setData({
      poster_url: detail
    })
  },

  /**
   * 页面的初始数据
   */
  data: {
    detail: null,
    param: {},
    resource: {},
    poster: '',
    canvasId: 'poster',
    qrcode: "",
    banner: "",
    logo: "",
    wechat:{},


    // 海报参数
    posterConfig: null,
    poster_url: null,

    //画布参数
    canvasParam:{
      x:0,
      y:0,
      width: 750,
      height: 900,
      bgColor:'#fff',
      fontSize:14,
      fontColor:'#000',
    }
  },
  create() {
    let resource = this.data.resource;
    let detail = this.data.detail;
    this.setData({
      posterConfig: {
        width: 800,
        height: 1200,
        backgroundColor: "#FFF",
        images: [
          {
            x: 0,
            y: 0,
            url: resource.banner,
            width: 800,
            height: 800
          },
          {
            x: 100,
            y: 920,
            zIndex: 800,
            url: resource.logo,
            width: 240,
            height: 190
          },
          {
            x: 450,
            y: 920,
            zIndex: 1000,
            url: resource.img,
            width: 250,
            height: 250
          }
        ],
        texts: [
          {
            x: 280,
            y: 860,
            text: detail.title,
            lineHeight: 50,
            fontSize: 34,
            fontWeight: 900,
            lineNum: 2,
            width: 450
          },
          {
            x: 0,
            y: 900,
            text: '￥' + detail.price,
            lineHeight: 70,
            fontSize: 60,
            lineNum: 1,
            color: '#ec0f0f',
            width: 450
          },
          {
            x: 210,
            y: 1110,
            text: '长按识别小程序二维码',
            lineHeight: 30,
            fontSize: 30,
            lineNum: 1,
            width: 540,
            zIndex: 1000,
            textAlign: 'center'
          },
          {
            x: 210,
            y: 1150,
            zIndex: 1000,
            text: '立即入住',
            lineHeight: 30,
            fontSize: 30,
            lineNum: 1,
            width: 540,
            textAlign: 'center'
          }
        ]
      }
    });
    wx.hideLoading()
    // 生成海报
    this.onCreatePoster();
    wx.hideLoading()
    // let _this = this;
    // let param = _this.data.canvasParam;
    // const ctx = wx.createCanvasContext(_this.data.canvasId);
    // //填充颜色
    // ctx.setFillStyle(param.bgColor)
    // //设置矩形
    // ctx.fillRect(param.x, param.y, param.width, param.height)
    // console.log(_this.data);
    // //开始作图
    // ctx.drawImage(_this.data.logo.path, 145, 10, 100, 60);
    // ctx.drawImage(_this.data.banner.path, 38, 80, 350, 200);
    // ctx.drawImage(_this.data.qrcode.path, 80, 370, 90, 90);
    // //文字水印
    // ctx.setFillStyle(param.fontColor);
    // ctx.setFontSize(param.fontSize);
    // ctx.fillText(_this.data.detail.title, 38, 300, 350);
    // ctx.setFillStyle('#ec0f0f');
    // ctx.setFontSize('18');
    // ctx.fillText('￥' + _this.data.detail.price, 38, 330, 350);
    // ctx.setFillStyle(param.fontColor);
    // ctx.setFontSize(param.fontSize);
    // ctx.fillText( '长按识别小程序二维码', 200, 400);
    // ctx.setFontSize('12');
    // ctx.fillText('立即入住', 240, 430);
    // //保存画布
    // ctx.draw(true, function () {
    //   setTimeout(function () {
    //     wx.canvasToTempFilePath({
    //       canvasId: _this.data.canvasId,
    //       destWidth: param.width,
    //       destHeight: param.height,
    //       quality: 1,
    //       fileType: 'jpg',
    //       success: function (res) {
    //         _this.setData({
    //           poster: res.tempFilePath
    //         });
    //         wx.hideLoading()
    //         // console.log(_this.data.poster)
    //       },
    //       fail: function (res) {
    //         console.log(res);
    //       }
    //     })
    //   }, 500)
    // });

  },
  getImages() {
    let _this = this;
    const wxgetImage = promisify(wx.getImageInfo)
    Promise.all([
      wxgetImage({
        src: _this.data.resource.img,
      }),
      wxgetImage({
        src: _this.data.resource.logo,
      }),
      wxgetImage({
        src: _this.data.resource.banner,
      })
    ]).then(res => {
      _this.setData({
        banner: res[2]
      })
      _this.setData({
        logo: res[1]
      })
      _this.setData({
        qrcode: res[0]
      })
      _this.create()
    })
  },

  /**
   * 获取详情
   */
  getProductDetail() {
    app.loading()
    let _this = this;
    app.HttpsRequest('product/detail', 'GET', _this.data.param).then(ret => {
    // app.HttpsRequest('product/detail', 'GET', {product_id: 15}).then(ret => {
      if (ret) {
        _this.setData({
          detail: ret.data
        })
        this.getPoster();
      }
    })
  },

  /**
   * 获取二维码
   */
  getPoster() {
    let _this = this;
    app.HttpsRequest('product/getQrcode', 'GET', {
      product_id: _this.data.param.product_id
      // product_id: 15
    }).then(ret => {
      if (ret) {
        _this.setData({
          resource: ret.data
        });
        _this.create()
      } else {
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/homestayDetails/index?product_id=' + _this.data.param.product_id
          })
        }, 1000);
      }
    })
  },
  savePhoto() {
    let _this = this;
    app.loading('正在保存...');
    setTimeout(() => {
      wx.saveImageToPhotosAlbum({
        filePath: _this.data.poster_url,
        success(res) {
          app.tips('保存成功');
        },
        fail() {
          app.tips('保存失败，请刷新页面重试');
        }
      })
    }, 2500)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let _this = this;
    _this.setData({
      param: options
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    app.loading();
    this.getProductDetail()
    this.setData({
      wechat:JSON.parse(wx.getStorageSync('wechat'))
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})